<template>
    <div class="VideoLobby">
        <div class="header-title">“西纳英才，名企引智” 大型网络视频招聘会</div>
        <div class="congtainer">
            <div class="pages-account-settings-info-main">
                <div class="main">
                    <div class="pages-account-settings-base-view-left">
                        <el-tabs v-model="activeName" @tab-click="handleClick">
                            <el-tab-pane label="求职大厅" name="0">
                                <el-row :gutter="20">
                                    <el-col v-for="(item, index) in customerUserList" :key="index" :span="8">
                                        <div class="grid-content bg-purple">
                                            <template v-if="item.jobSeeker">
                                                <el-card class="box-card" style="margin-bottom: 15px;">
                                                    <div class="row">
                                                        <div>
                                                            <img class="avatar" :src="BASEURL + item.jobSeeker.avatar" alt="">
                                                            
                                                        </div>
                                                        <div class="flex-grow-1 post-content">
                                                            <div class="post-text">{{item.jobSeeker.name}}</div>
                                                            <el-popover
                                                                placement="right-start"
                                                                title="求职名称"
                                                                width="150"
                                                                trigger="hover"
                                                                :content="item.jobSeeker.param1">
                                                                <div slot="reference" class="post-text">{{item.jobSeeker.param1}}</div>
                                                            </el-popover>
                                                            <div v-if="item.connected == '0'">空闲</div>
                                                            <div v-if="item.connected == '1'">通话中</div>
                                                        </div>
                                                        <div class="video-conect" v-if="globalUserInfoRoleId !== '0'">
                                                            <i @click="handleConectVideo(item)" class="iconfont icon-shipin"></i>
                                                        </div>
                                                    </div>
                                                <!-- {{item}} -->
                                                </el-card>
                                            </template>
                                            
                                        </div>
                                    </el-col>
                                </el-row>

                                <div class="row jcc">
                                    <el-pagination
                                    :page-size="customerUserListpageSize"
                                    layout="prev, pager, next"
                                    @current-change="handleCurrentChange"
                                    :total="customerUserListtotal">
                                    </el-pagination>
                                </div>
                                
                            </el-tab-pane>
                            <el-tab-pane label="招聘大厅" name="1">
                                <el-row :gutter="20">
                                    <el-col v-for="(item, index) in enterpriseUserList" :key="index" :span="8">
                                        <div class="grid-content bg-purple">
                                            <template v-if="item.company">
                                                <el-card class="box-card" style="margin-bottom: 15px;">
                                                    <div class="row">
                                                        <div>
                                                            <img class="avatar" :src="BASEURL + item.company.logo" alt="">
                                                        </div>
                                                        <div class="flex-grow-1 post-content">
                                                            <div class="post-text">{{item.company.name}}</div>
                                                            <div v-if="item.company.jobList && item.company.jobList.length > 0">
                                                                <el-popover
                                                                    placement="right-start"
                                                                    title="求职名称"
                                                                    width="500"
                                                                    trigger="hover"
                                                                    style="cursor: pointer;"
                                                                    >
                                                                    <el-table :data="item.company.jobList">
                                                                        <el-table-column width="150" property="posName" label="招聘职位"></el-table-column>
                                                                        <el-table-column width="120" property="salary" label="薪资待遇"></el-table-column>
                                                                        <el-table-column width="100" property="linkman" label="HR姓名"></el-table-column>
                                                                        <el-table-column width="150" property="mobile" label="联系电话"></el-table-column>
                                                                        <el-table-column width="100" property="education" label="学历要求"></el-table-column>
                                                                        <el-table-column width="100" property="age" label="年龄要求"></el-table-column>
                                                                        <el-table-column width="100" property="posArea" label="工作城市"></el-table-column>
                                                                        <el-table-column width="200" property="address" label="详细地址"></el-table-column>

                                                                    </el-table>
                                                                    <div slot="reference" class="post-text">有{{item.company.jobList.length}}条职位信息</div>
                                                                </el-popover>
                                                                
                                                            </div>
                                                            <div v-if="item.company.jobList && item.company.jobList.length == 0" class="post-text">
                                                                暂无发布职位信息
                                                            </div>
                                                            <div v-if="item.connected == '0'">空闲</div>
                                                            <div v-if="item.connected == '1'">通话中</div>
                                                        </div>
                                                        <div class="video-conect" v-if="globalUserInfoRoleId !== '1'">
                                                            <i @click="handleConectVideo(item)" class="iconfont icon-shipin"></i>
                                                        </div>
                                                    </div>
                                                <!-- {{item}} -->
                                                </el-card>
                                            </template>
                                            
                                        </div>
                                    </el-col>
                                </el-row>

                                <div class="row jcc">
                                    <el-pagination
                                    :page-size="enterpriseUserListpageSize"
                                    layout="prev, pager, next"
                                    @current-change="handleEnterpriseCurrentChange"
                                    :total="enterpriseUserListtotal">
                                    </el-pagination>
                                </div>
                            </el-tab-pane>
                        </el-tabs>
                        
                    </div>

                    <div class="pages-account-settings-base-view-right">
                        <el-card class="box-card" shadow="never" style="border: 0;">
                            <div slot="header" class="clearfix is-active">
                                <span>统计</span>
                            </div>
                            <div class="row jcsb statistics">
                                <div><CommunicationAterList model="1" text="已沟通过"></CommunicationAterList></div>
                                <span>|</span>       
                                <div><CommunicationAterList model="3" text="已拒接"></CommunicationAterList></div>
                                <span>|</span>
                                <div><CommunicationAterList model="2" text="未接通"></CommunicationAterList></div>
                            </div>
                        </el-card>
                        <el-card class="box-card" shadow="never" style="border: 0;">
                            <div slot="header" class="clearfix is-active">
                                <span>温馨提示</span>
                            </div>
                            <div class="column jcsb statistics">
                                <p>1、当出现连接失败或者视频加载不出的情况请刷新浏览器重试；</p>
                                <p>2、为了方便使视频通话顺畅请使用最新版谷歌浏览器；</p>
                            </div>
                        </el-card>

                    </div>

                </div>
            </div>
        </div>

        <template v-if="localplayerDialogVisible">
            <el-dialog
            :visible.sync="localplayerDialogVisible"
            width="80%"
            :show-close="false"
            :close-on-click-modal="false"
            > 
            <div class="row video-window jcc">
                <div id="localplayer"></div>
                <div id="remoteplayer"></div>
                <div class="operation-grow">
                    <div class="close" @click="handleLocalplayerDialogVisibleClose">
                        <img src="@/assets/conectVideo/closeVideo.png" alt="">
                    </div>
                </div>
            </div>
            
            <!-- <span slot="footer" class="dialog-footer">
                <el-button @click="handleLocalplayerDialogVisibleClose">取 消</el-button>
                <el-button type="primary" @click="handleLocalplayerDialogVisibleClose">确 定</el-button>
            </span> -->
            </el-dialog>
        </template>
        
        <template v-if="informState">
            <ConectVideoInform 
            :state="informState" 
            :fromUsername = "fromUsername"
            @handlesuccess="handleConectInformSuccess"
            @handleFailed="handleConectInformError"
            ></ConectVideoInform>
        </template>

        <template v-if="isTimerSix">
            <TimerSix :cancel="isTimerSix" @timerPassSixtySeconds="timerPassSixtySeconds"></TimerSix>
        </template>
    </div>
</template>

<script>
import sock from '@/common/socket';
import { BASEURL } from "@/api/";
import { Reponse } from '@/common/utils'
// import * as QNRTC from "pili-rtc-web";
import {myRTC, QNRTC} from '@/common/myRTC'
import ConectVideoInform from '@/components/ConectVideoInform'
import TimerSix from '@/components/TimerSix'
import CommunicationAterList from '@/components/CommunicationAterList'


export default {
  computed: {
      globalUserId(){
          return this.$store.state.home.globalUserInfo.userId;
      },
      globalUserInfoRoleId(){
          return this.$store.state.home.globalUserInfo.roleId;
      },
      globalUserInfo(){
          return this.$store.state.home.globalUserInfo;
      }
  },
  data() {
    return {
      activeName: this.$route.params.state,
      customerUserList: [],
      enterpriseUserList: [],
      jobFair: '',
      BASEURL,
      customerUserListpageSize: 24,
      customerUserListpaegNumber: 1,
      customerUserListtotal: 0,
      enterpriseUserListpageSize: 24,
      enterpriseUserListpaegNumber: 1,
      enterpriseUserListtotal: 0,
      
      roomToken: '',
      localplayerDialogVisible: false,  //视频窗口
      toId: '',    //邀请人userid
      fromId: '',  //接受人userid
      hisId: '',  //面试记录id

      informState: false,

      getFromRoomTokenData: '',
      getToRoomTokenData: '',

      refreshState: false, //刷新状态

      fullscreenLoading: false,

      fromUsername: '',  //发起人用户名

      isTimerSix:false
    };
  },
  mounted(){
      console.log(this.globalUserInfoRoleId)
      this.init();
    //   发起面试者返回事件
      this.getFromRoomToken();
    // 收到面试通知者返回时间
      this.getToRoomToken();
      
      this.disconect();
  },

  methods: {
      handleClick(tab, event) {
        // console.log(tab, event);
      },

      disconect(){
          sock.on('disconnect',(res)=>{
            this.informState = false;
            console.log(res,'disconnect');
            res.data && this.$message.info(res.data);
            if(res.user == "发起人"){
                this.disConectVideo(myRTC);
                setTimeout(()=>{
                    // location.reload();
                    this.$emit('handleReload',false)
                },500)
            }else{
            // this.$message.info("对方已挂断");
                if(this.refreshState){
                    setTimeout(()=>{
                        // location.reload();
                        this.disConectVideo(myRTC);
                        this.$emit('handleReload',false)
                    },500)
                }else{
                    this.disConectVideo(myRTC);
                }
            }
            
          })
      },

    //   初始化用户列表
      init(){
        this.customerUserList = [];
        this.enterpriseUserList = [];
        sock.emit('enterJobFair', { userId: this.globalUserId, jobFairId: this.$route.params.jobFairId });
        // sock.on('getJobFairInfo',(data)=>{
        //     console.log(data.jobFairId == this.$route.params.jobFairId)
        //     if(data.jobFairId !== this.$route.params.jobFairId) return;
        // })
        sock.on('listUsers',(data)=>{
            // console.log(data.jobFair.jobFairId == this.$route.params.jobFairId)
            // if(data.jobFair.jobFairId !== this.$route.params.jobFairId) return;
            console.log(data,'socket')
            let customerUserList = [];
            let enterpriseUserList = [];
            if(data.userList !== null && data.userList.length == 0 ) return;
            if(this.$route.params.jobFairId == undefined) return;
            data.userList[this.$route.params.jobFairId].map((val)=>{
                console.log(val.roleId)
                if(val.roleId == '0'){
                    customerUserList = [...customerUserList].concat(val);
                    
                    this.customerUserList = customerUserList;


                }else if(val.roleId == '1'){
                    enterpriseUserList = [...enterpriseUserList].concat(val);
                    this.enterpriseUserList = enterpriseUserList;
                }
            })

            let customerUserListRes = new Reponse().splitPage(customerUserList, this.customerUserListpageSize, this.customerUserListpaegNumber).run().data;
            let enterpriseUserListRes = new Reponse().splitPage(enterpriseUserList, this.enterpriseUserListpageSize, this.enterpriseUserListpaegNumber).run().data;

            this.customerUserList = customerUserListRes.rows;
            this.customerUserListtotal = customerUserListRes.total;

            this.enterpriseUserList = enterpriseUserListRes.rows;
            this.enterpriseUserListtotal = enterpriseUserListRes.total;
            console.log(customerUserListRes,enterpriseUserListRes)
            console.log(this.enterpriseUserList)
            // this.userList = res.rows;
            // this.total = res.total;
        })
        
      },
     
    //   发起视频面试
      handleConectVideo(data){
        if(data.connected == '1'){
            this.$message.error('当前用户正在通话中，请稍后重试');
            return
        }
        //   sock.emit('enterJobFair', { userId: this.globalUserId, jobFairId: this.$route.params.jobFairId });
        switch (data.roleId) {
            case '0':
                this.toId = data.userId;
                sock.emit('createRoom', {
                     jobFairId: this.$route.params.jobFairId, 
                     fromId: this.globalUserId,
                     fromName: this.globalUserInfo.company.name,
                     toId: data.userId,
                     toName:data.jobSeeker.name
                });
                break;
            
            case '1':
                this.toId = data.userId;
                console.log({
                     jobFairId: this.$route.params.jobFairId, 
                     fromId: this.globalUserId,
                     fromName: this.globalUserInfo.jobSeeker.name,
                     toId: data.userId,
                     toName:data.company.name
                })
                sock.emit('createRoom', {
                     jobFairId: this.$route.params.jobFairId, 
                     fromId: this.globalUserId,
                     fromName: this.globalUserInfo.jobSeeker.name,
                     toId: data.userId,
                     toName:data.company.name
                });
                break;
        
            default:
                break;
        }
      },
    //   发起面试的返回值(发起人监听事件）
      getFromRoomToken(){
          sock.on('getFromRoomToken',(data)=>{
              this.$message.success("正在呼叫，请稍等...");
              this.getFromRoomTokenData = data;
              console.log(data,'发起面试者返回事件')
              this.conectVideo(data.roomToken);
              this.localplayerDialogVisible = true;
            //   this.informState = true;
              this.toId = data.toId;
              this.fromId = data.fromId;
              this.hisId = data.hisId;
            //   this.interviewSuccess(data);
          })
      },
    //   发起面试的返回值(接受人监听事件）
      getToRoomToken(){
          sock.on('getToRoomToken',(data)=>{
            this.getToRoomTokenData = data;
            console.log(data,'收到面试通知者返回时间')
            this.informState = true;
            this.toId = data.toId;
            this.fromId = data.fromId;
            this.hisId = data.hisId;
            this.fromUsername = data.fromUsername;
            //点击同意面试
            this.interviewSuccess(data);
            // this.acceptInterview(data)

            this.cancelInterview(true)
          })
      },

    //   取消面试
      cancelInterview(data){
        this.isTimerSix = true;
      },

      timerPassSixtySeconds(){
          sock.emit('cancelInterview', {
            jobFairId: this.$route.params.jobFairId, 
            fromId: this.fromId,
            hisId: this.hisId,
            toId: this.toId
        });
          this.isTimerSix = false;
      },

      handleCurrentChange(page){
          console.log(page)
          this.customerUserListpaegNumber = page;
          this.init()
      },
      handleEnterpriseCurrentChange(page){
          this.enterpriseUserListpaegNumber = page;
          this.init()
      },
      
    //   视频链接
      async conectVideo(roomToken){
        // const myRTC = new QNRTC.TrackModeSession();
        console.log(roomToken,'roomTokenroomTokenroomTokenroomTokenroomTokenroomTokenroomToken')
        // const myRTC = new QNRTC.TrackModeSession();
        try {
            await myRTC.joinRoomWithToken(roomToken);

            await this.publish(myRTC);

            this.autoSubscribe(myRTC);
            this.isTimerSix = false;

        } catch (e) {
            console.error('error!', e);
        }
      },

    // 采集本地视频音频流
      async  publish(myRoom) {
        const localTracks = await QNRTC.deviceManager.getLocalTracks({
            audio:  { enabled: true, tag: "audio" },
            video:  { enabled: true, tag: "video" },
            // screen: { enabled: true, tag: "screen" },
        });
        console.log("my local tracks", localTracks);
        // 将刚刚的 Track 列表发布到房间中
        await myRoom.publish(localTracks);
        console.log("publish success!");

        // 获取页面上的一个元素作为播放画面的父元素
        const localElement = document.getElementById("localplayer");
        // 遍历本地采集的 Track 对象
        for (const localTrack of localTracks) {
            // 如果这是麦克风采集的音频 Track，我们就不播放它。
            if (localTrack.info.tag === "audio") continue;
            // 调用 Track 对象的 play 方法在这个元素下播放视频轨
            localTrack.play(localElement, true);
        
        }
      },

        autoSubscribe(myRoom) {
            const trackInfoList = myRoom.trackInfoList;
            console.log("room current trackInfo list", trackInfoList)

            // 调用我们刚刚编写的 subscribe 方法
            // 注意这里我们没有使用 async/await，而是使用了 Promise，大家可以思考一下为什么
            this.subscribe(myRoom, trackInfoList)
                .then(() => console.log("subscribe success!"))
                .catch(e => console.error("subscribe error", e));

            // 添加事件监听，当房间中出现新的 Track 时就会触发，参数是 trackInfo 列表
            myRoom.on("track-add", (trackInfoList) => {
                console.log("get track-add event!", trackInfoList);
                this.subscribe(myRoom, trackInfoList)
                .then(() => console.log("subscribe success!"))
                .catch(e => console.error("subscribe error", e));
            });

            // 就是这样，就像监听 DOM 事件一样通过 on 方法监听相应的事件并给出处理函数即可
        },

      async subscribe(myRoom, trackInfoList) {
          
          console.log(trackInfoList)
        // 通过传入 trackId 调用订阅方法发起订阅，成功会返回相应的 Track 对象，也就是远端的 Track 列表了
        const remoteTracks = await myRoom.subscribe(trackInfoList.map(info => info.trackId));

        // 选择页面上的一个元素作为父元素，播放远端的音视频轨
        const remoteElement = document.getElementById("remoteplayer");
        // 遍历返回的远端 Track，调用 play 方法完成在页面上的播放
        for (const remoteTrack of remoteTracks) {
            remoteTrack.play(remoteElement);
        }

        
    },

    //   关闭视频弹窗
      handleLocalplayerDialogVisibleClose(){
          console.log({ 
            "jobFairId": this.$route.params.jobFairId, 
            "fromId": this.fromId,
            "toId": this.toId,
            })
          sock.emit('hungup',{ 
            "jobFairId": this.$route.params.jobFairId, 
            "fromId": this.fromId,
            "toId": this.toId,
            "userId": this.globalUserId,
            })
          
      },

      async disConectVideo(myRoom){
          const trackInfoList = myRoom.trackInfoList;
          console.log(myRoom.users,myRoom.trackInfoList,'disConectVideodisConectVideodisConectVideodisConectVideodisConectVideodisConectVideodisConectVideodisConectVideodisConectVideo')
        //   const disConectTracksPublish = await myRoom.unpublish(trackInfoList.map(info => info.trackId));
          console.log(myRoom.trackInfoList)
          const disConectTracksSubscribe = await myRoom.unsubscribe(trackInfoList.map(info => info.trackId));
          console.log(myRoom.trackInfoList)
        //   QNRTC.release()
          myRoom.leaveRoom();
          this.localplayerDialogVisible = false;
      },

    //   视频通知同意
      handleConectInformSuccess(res){
        this.refreshState = true;
        this.acceptInterview();
      },
    
    //   视频通知拒绝
      handleConectInformError(res){
        this.refreshState = false;
        this.rejectInterview();
      },


      
    //   接受面试请求
      acceptInterview(){
          sock.emit('acceptInterview',{
            "jobFairId": this.$route.params.jobFairId,
            "fromId": this.fromId,
            "toId": this.toId,
            "hisId": this.hisId,
          })
      },
      //   接受面试返回
      interviewSuccess(data){
          sock.on('interviewSuccess',()=>{
            this.cancelInterview(false)
            //   this.getToRoomToken();
            this.localplayerDialogVisible = true;
            this.informState = false;
            this.conectVideo(data.roomToken);
          })
      },

      //   拒绝面试请求
      rejectInterview(){
          sock.emit('rejectInterview',{
            "jobFairId": this.$route.params.jobFairId,
            "fromId": this.fromId,
            "toId": this.toId,
            "hisId": this.hisId,
          })
          sock.on('interviewFailed',()=>{
          
          })
      },
      //   拒绝面试返回
      interviewFailed(data){
          
      }

  },
  components:{
      ConectVideoInform,
      TimerSix,
      CommunicationAterList,
  }
}
</script>

<style lang="less">
.VideoLobby{
  .congtainer {
    //   background: #f3f8ff;
  }
  .header-title {
      height: 120px;
      background: #f3f8ff;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 26px;
      
  }
  .pages-account-settings-info-main {
    width: 1200px;
    margin: 0 auto;
    height: 100%;
    background-color: #fff;
    display: flex;
    padding-top: 16px;
    padding-bottom: 16px;
    overflow: auto;

    .main {
        flex: 1 1;
        padding: 8px 0;
        display: flex;

        .pages-account-settings-base-view-left {
            flex: 2;
            .avatar {
                width: 30px;
                height: 30px;
                margin-right: 15px;
            }
            .video-conect {
                .iconfont {
                    font-size: 24px;
                    cursor: pointer;
                }
            }

            .post-content {
                width: 10px;
            }
            .post-text {
                overflow: hidden;    
                text-overflow: ellipsis;
                white-space: nowrap;
                width: 130px;
                
            }
        }
        .pages-account-settings-base-view-right {
            flex: 1;
            margin-left: 15px;
            border-left: 1px solid #ebeef5;
            padding-left: 15px;

            .statistics {
                div {
                    cursor: pointer;
                }
            }
        }

    }
  }

  .video-window {
      position: relative;
      
      .operation-grow {
          position:absolute;
          bottom: 30px;
          .close {
              height: 50px;
              background: #fff;
              border-radius: 50%;
              cursor: pointer;
              img{
                  height: 100%;
              }
          }
      }
  }
}
</style>
